package rejjie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.bind.annotation.*;
import rejjie.common.R;
import rejjie.dto.DishDto;
import rejjie.entity.Category;
import rejjie.entity.Dish;
import rejjie.entity.DishFlavor;
import rejjie.service.CategoryService;
import rejjie.service.DishFlavorService;
import rejjie.service.DishService;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")

public class DishController {


    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        dishService.saveWithFlavor(dishDto);
        return R.success("菜品增加成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){

        log.info("{},{},{}",page,pageSize,name);
        // 构建page对象
        Page<Dish> pageinfo = new Page(page,pageSize);
        Page<DishDto> dishDtoPage = new Page();

        //构建查询条件
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper();

        lambdaQueryWrapper.like(name!=null,Dish::getName,name).orderByAsc(Dish::getUpdateTime);
        dishService.page(pageinfo,lambdaQueryWrapper);

        // 把查询得到的page赋给另外的对象 除了page对象中的record记录（里面存储的一条条的Dish对象） 剩下的说就是total 那些东西
        BeanUtils.copyProperties(pageinfo,dishDtoPage,"records");

        List<Dish> records = pageinfo.getRecords();
        List<DishDto> dishDtoList = records.stream().map((item)->{
            DishDto dishDto = new DishDto();

            // 把每一条dish记录中的属性值 复制到 dishDto中
            BeanUtils.copyProperties(item,dishDto);

            // 查询种类名并且进行赋值
            Long categoryId = item.getCategoryId();
            Category cag = categoryService.getById(categoryId);
            if(cag!=null) {
                String cagName = cag.getName();
                dishDto.setCategoryName(cagName);
            }
            return dishDto;
        }).collect(Collectors.toList());

        // 把得到的信息赋值给那个列表
        dishDtoPage.setRecords(dishDtoList);
        return R.success(dishDtoPage);
    }

    /**
     * 我们要去得到菜品的口味
     * @param id
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto byIdWithFlavor = dishService.getByIdWithFlavor(id);
        return R.success(byIdWithFlavor);
    }

    /**
     * 在我们进行更新的时候，我们不仅需要对dish表进行操作
     * 同时需要对dishflavor表进行操作。
     * 所以我们采取的方式更改dish表
     * 然后对dishflavor表中的相关数据进行删除之后再重新插入
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info("{}",dishDto);
        dishService.updateById(dishDto);

        // 得到菜品的id 删除dishFlavor中数据
        LambdaQueryWrapper<DishFlavor> dishflavorQw= new LambdaQueryWrapper();
        dishflavorQw.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(dishflavorQw);

        // 重新插入相关数据
        // 但是因为一些问题
        List<DishFlavor> flavors = dishDto.getFlavors();

        flavors = flavors.stream().map((item)->{
            log.info("{}",item);
            item.setDishId(dishDto.getId());
            log.info("{},{},{}",item.getDishId(),dishDto.getId(),item.getDishId()==dishDto.getId());
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);

        return R.success("菜品修改成功");
    }

    /**
     * 后端是
     * 根据对应的条件得到我们想要的菜品列表
     *
     * 手机端是
     * 根据对应的条件除了得到我们想要的菜品，同时还要得到我们想要的口味列表
     * 口味别封装的dishDto中
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        log.info("{}，{}",dish.getCategoryId(),dish.getStatus());

        // 根据类别查到 该类有那些菜
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        dishLambdaQueryWrapper.eq(Dish::getStatus,1);
        List<Dish> dishList = dishService.list(dishLambdaQueryWrapper);

        // 再根据菜品的id, 去查询该菜有那些口味
         List<DishDto>  dishDtoList = dishList.stream().map((item)->{
             DishDto dishDto = new DishDto();
             BeanUtils.copyProperties(item,dishDto);

             // 查询的种类名 赋值给他

             Category category = categoryService.getById(item.getCategoryId());
             if (category != null) {
                 dishDto.setCategoryName(category.getName());
             }

             // 查询的口味表
             LambdaQueryWrapper<DishFlavor> dishFlavorlambdaQueryWrapper =new LambdaQueryWrapper();
             dishFlavorlambdaQueryWrapper.eq(DishFlavor::getDishId,item.getId());
             List<DishFlavor> dishFlavors = dishFlavorService.list(dishFlavorlambdaQueryWrapper);
             dishDto.setFlavors(dishFlavors);
             return dishDto;
         }).collect(Collectors.toList());



        return R.success(dishDtoList);
    }

}
